<?php
namespace App\Handler;


use App\Models\Teacher;
use Illuminate\Support\Facades\Log;
use p5\objects\FileUtils;

/**
 * Created by PhpStorm.
 * User: Adam
 * Date: 2016/5/10
 * Time: 14:31
 */
class CommHandler
{

    public static function copyImageFile($filename, $targetPath = "", $isCover = false)
    {
        /**
         * $filename= $bean->get_header_file();
         * $targetPath= "teacher/"
         */
        self::copyFile($filename, $targetPath, $isCover);
    }


    public static function copyFile($filename, $targetPath = "", $isCover = false)
    {
        /**
         * //$filename= $bean->get_header_file();
         * $targetPath= "teacher/"
         */
        $uploadRoot = env("UI_UPLOAD_ROOT", "d:/temp/");
        $targetRoot = env("UI_SITE_ROOT", "d:/temp/") . "app/files/" . $targetPath;
        $dir = FileUtils::get_file_path($filename);
        if (!file_exists($targetRoot . $dir)) {
            mkdir($targetRoot . $dir, 0777, true);
        }
        $fromFile = $uploadRoot . $filename;
        Log::debug("copy $fromFile to $targetRoot ");
        if (!file_exists($fromFile) || (!is_file($fromFile))) {
            Log::error("$fromFile 不存在或者不是有效的文件");
            return;
        }
        $targetFile = $targetRoot . $filename;
        if (file_exists($targetFile) && (!$isCover)) {
            Log::error("$targetFile 已经存在，跳过复制");
            return;
        }
        if (!copy($fromFile, $targetFile)) {
            if (!file_exists($targetFile)) {
                unlink($targetFile);
                copy($fromFile, $targetFile);
            }
        }
        if (!file_exists($targetFile)) {
            Log::error("$fromFile 拷贝到 $targetFile 失败");
        }
    }

}